<template>
  <div class="order-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <a-button @click="router.back()">
          <template #icon><icon-left /></template>
          返回列表
        </a-button>
        <a-divider direction="vertical" />
        <h2 class="page-title">订单详情</h2>
        <a-tag :color="getStatusColor(orderInfo.status)" size="medium">
          {{ getStatusText(orderInfo.status) }}
        </a-tag>
      </div>
      <div class="header-right">
        <a-space>
          <a-button @click="handlePrint">
            <template #icon><icon-printer /></template>
            打印订单
          </a-button>
          <a-button type="primary" @click="handleExport">
            <template #icon><icon-download /></template>
            导出订单
          </a-button>
        </a-space>
      </div>
    </div>

    <div class="detail-content">
      <!-- 订单状态卡片 -->
      <a-card class="status-card" :bordered="false">
        <div class="status-header">
          <div class="status-info">
            <icon-check-circle-fill class="status-icon" />
            <div class="status-text">
              <div class="status-title">
                {{ getStatusText(orderInfo.status) }}
              </div>
              <div class="status-desc">
                订单已于 {{ orderInfo.createTime }} 创建完成
              </div>
            </div>
          </div>
          <div class="status-actions">
            <template v-if="orderInfo.status === 'pending_delivery'">
              <a-button type="primary" status="success" @click="handleDeliver">
                <template #icon><icon-send /></template>
                发货
              </a-button>
            </template>
            <template v-if="orderInfo.status === 'pending_payment'">
              <a-button type="primary" status="warning" @click="handleCancel">
                <template #icon><icon-close /></template>
                取消订单
              </a-button>
            </template>
            <a-button @click="handleRemark">
              <template #icon><icon-edit /></template>
              添加备注
            </a-button>
          </div>
        </div>
        <a-steps
          :current="getStatusStep(orderInfo.status)"
          class="status-steps"
        >
          <a-step title="提交订单" :description="orderInfo.createTime">
            <template #icon><icon-file-done /></template>
          </a-step>
          <a-step title="付款成功" :description="orderInfo.payTime">
            <template #icon><icon-wallet /></template>
          </a-step>
          <a-step title="商家发货" :description="orderInfo.deliveryTime">
            <template #icon><icon-send /></template>
          </a-step>
          <a-step title="交易完成" :description="orderInfo.completeTime">
            <template #icon><icon-check-circle /></template>
          </a-step>
        </a-steps>
      </a-card>

      <a-row :gutter="16" class="detail-row">
        <!-- 左侧信息区域 -->
        <a-col :span="16">
          <!-- 商品信息 -->
          <a-card class="detail-card" title="商品信息" :bordered="false">
            <template #extra>
              <a-tag>共 {{ orderInfo.products?.length || 1 }} 件商品</a-tag>
            </template>
            <div class="products-list">
              <div
                v-for="(product, index) in orderInfo.products"
                :key="index"
                class="product-item"
              >
                <a-image :src="product.image" :width="80" :height="80" />
                <div class="product-info">
                  <div class="product-name">{{ product.name }}</div>
                  <div class="product-specs">{{ product.specs }}</div>
                  <div class="product-price">
                    <span class="price">¥{{ product.price }}</span>
                    <span class="quantity">x{{ product.quantity }}</span>
                  </div>
                </div>
              </div>
            </div>
            <a-divider />
            <div class="order-amount">
              <div class="amount-item">
                <span>商品总价：</span>
                <span>¥{{ orderInfo.totalAmount }}</span>
              </div>
              <div class="amount-item" v-if="orderInfo.discountAmount > 0">
                <span>优惠金额：</span>
                <span class="discount">-¥{{ orderInfo.discountAmount }}</span>
              </div>
              <div class="amount-item">
                <span>运费：</span>
                <span>¥{{ orderInfo.shippingFee }}</span>
              </div>
              <div class="amount-item total">
                <span>实付金额：</span>
                <span class="total-price">¥{{ orderInfo.payAmount }}</span>
              </div>
            </div>
          </a-card>

          <!-- 物流信息 -->
          <a-card
            v-if="orderInfo.status !== 'pending_payment'"
            class="detail-card"
            title="物流信息"
            :bordered="false"
          >
            <template #extra>
              <a-button type="text" @click="handleRefreshLogistics">
                <template #icon><icon-refresh /></template>
                刷新
              </a-button>
            </template>
            <div class="logistics-info">
              <div class="express-info">
                <icon-local-shipping class="express-icon" />
                <div class="express-detail">
                  <div class="express-company">
                    {{ orderInfo.expressCompany }}
                  </div>
                  <div class="express-number">
                    运单号：{{ orderInfo.expressNo }}
                    <a-button
                      type="text"
                      size="mini"
                      @click="handleCopyTrackingNo"
                    >
                      <template #icon><icon-copy /></template>
                      复制
                    </a-button>
                  </div>
                </div>
              </div>
              <a-timeline class="logistics-timeline">
                <a-timeline-item
                  v-for="(item, index) in logisticsInfo"
                  :key="index"
                  :dot-color="index === 0 ? '#165DFF' : ''"
                >
                  <div class="timeline-content">
                    <div class="timeline-text">{{ item.content }}</div>
                    <div class="timeline-time">{{ item.time }}</div>
                  </div>
                </a-timeline-item>
              </a-timeline>
            </div>
          </a-card>

          <!-- 操作日志 -->
          <a-card class="detail-card" title="操作日志" :bordered="false">
            <a-table
              :columns="logColumns"
              :data="operationLogs"
              :pagination="false"
            >
              <template #operator="{ record }">
                <span>{{ record.operator }}</span>
                <a-tag
                  v-if="record.role"
                  size="small"
                  style="margin-left: 8px"
                  >{{ record.role }}</a-tag
                >
              </template>
            </a-table>
          </a-card>
        </a-col>

        <!-- 右侧信息区域 -->
        <a-col :span="8">
          <!-- 买家信息 -->
          <a-card class="detail-card" title="买家信息" :bordered="false">
            <template #extra>
              <a-button type="text" @click="handleCopyBuyerInfo">
                <template #icon><icon-copy /></template>
                复制
              </a-button>
            </template>
            <div class="info-list">
              <div class="info-item">
                <span class="label">买家昵称：</span>
                <span class="value">{{ orderInfo.buyer.name }}</span>
                <a-tag v-if="orderInfo.buyer.isNew" color="blue" size="small"
                  >新客户</a-tag
                >
              </div>
              <div class="info-item">
                <span class="label">联系电话：</span>
                <span class="value">{{ orderInfo.buyer.phone }}</span>
              </div>
              <div class="info-item">
                <span class="label">收货地址：</span>
                <span class="value">{{ orderInfo.buyer.address }}</span>
              </div>
            </div>
          </a-card>

          <!-- 支付信息 -->
          <a-card class="detail-card" title="支付信息" :bordered="false">
            <div class="info-list">
              <div class="info-item">
                <span class="label">支付方式：</span>
                <span class="value">{{ orderInfo.payMethod }}</span>
              </div>
              <div class="info-item">
                <span class="label">支付时间：</span>
                <span class="value">{{ orderInfo.payTime }}</span>
              </div>
              <div class="info-item">
                <span class="label">交易单号：</span>
                <span class="value">{{ orderInfo.transactionId }}</span>
                <a-button
                  type="text"
                  size="mini"
                  @click="handleCopyTransactionId"
                >
                  <template #icon><icon-copy /></template>
                  复制
                </a-button>
              </div>
            </div>
          </a-card>

          <!-- 订单信息 -->
          <a-card class="detail-card" title="订单信息" :bordered="false">
            <div class="info-list">
              <div class="info-item">
                <span class="label">订单编号：</span>
                <span class="value">{{ orderInfo.orderNo }}</span>
                <a-button type="text" size="mini" @click="handleCopyOrderNo">
                  <template #icon><icon-copy /></template>
                  复制
                </a-button>
              </div>
              <div class="info-item">
                <span class="label">下单时间：</span>
                <span class="value">{{ orderInfo.createTime }}</span>
              </div>
              <div class="info-item">
                <span class="label">订单来源：</span>
                <span class="value">
                  <icon-mobile v-if="orderInfo.source === 'mobile'" />
                  <icon-computer v-if="orderInfo.source === 'pc'" />
                  {{ getSourceText(orderInfo.source) }}
                </span>
              </div>
              <div class="info-item">
                <span class="label">订单备注：</span>
                <span class="value">{{ orderInfo.remark || "暂无备注" }}</span>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 发货弹窗 -->
    <a-modal
      v-model:visible="deliverVisible"
      title="订单发货"
      @ok="handleDeliverSubmit"
      @cancel="handleDeliverCancel"
    >
      <a-form :model="deliverForm" layout="vertical">
        <a-form-item field="company" label="快递公司" required>
          <a-select
            v-model="deliverForm.company"
            placeholder="请选择快递公司"
            allow-clear
          >
            <a-option
              v-for="item in expressOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="number" label="快递单号" required>
          <a-input
            v-model="deliverForm.number"
            placeholder="请输入快递单号"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="remark" label="发货备注">
          <a-textarea
            v-model="deliverForm.remark"
            placeholder="请输入发货备注"
            :max-length="200"
            show-word-limit
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 备注弹窗 -->
    <a-modal
      v-model:visible="remarkVisible"
      title="订单备注"
      @ok="handleRemarkSubmit"
      @cancel="handleRemarkCancel"
    >
      <a-form :model="remarkForm" layout="vertical">
        <a-form-item field="content" label="备注内容">
          <a-textarea
            v-model="remarkForm.content"
            placeholder="请输入备注内容"
            :max-length="500"
            show-word-limit
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Message } from "@arco-design/web-vue";
import {
  IconLeft,
  IconPrinter,
  IconDownload,
  IconCheckCircle,
  IconCheckCircleFill,
  IconSend,
  IconClose,
  IconEdit,
  IconFileDone,
  IconWallet,
  IconRefresh,
  IconCopy,
  IconMobile,
  IconComputer,
  IconLocalShipping,
} from "@arco-design/web-vue/es/icon";

const router = useRouter();
const route = useRoute();

// 订单信息
const orderInfo = ref({
  id: route.params.id,
  orderNo: "SO2024031500001",
  status: "delivered",
  createTime: "2024-03-15 12:34:56",
  payTime: "2024-03-15 12:35:00",
  deliveryTime: "2024-03-15 14:20:30",
  completeTime: "2024-03-18 15:30:00",
  products: [
    {
      image: "https://example.com/image1.jpg",
      name: "特色桂花糕",
      specs: "规格：500g/盒",
      price: 299.0,
      quantity: 1,
    },
  ],
  totalAmount: 299.0,
  discountAmount: 0,
  shippingFee: 0,
  payAmount: 299.0,
  buyer: {
    name: "张三",
    phone: "13888888888",
    address: "广西壮族自治区贵港市港北区贵港大道123号",
    isNew: true,
  },
  expressCompany: "顺丰速运",
  expressNo: "SF1234567890123",
  payMethod: "微信支付",
  transactionId: "4200000001202403150123456789",
  source: "mobile",
  remark: "请尽快发货，谢谢！",
});

// 物流信息
const logisticsInfo = ref([
  {
    content: "已签收，签收人：张三",
    time: "2024-03-18 15:30:00",
  },
  {
    content: "【贵港市】快件已到达贵港市港北区网点",
    time: "2024-03-17 09:30:00",
  },
  {
    content: "【南宁市】快件已从南宁转运中心发出",
    time: "2024-03-16 18:20:00",
  },
  {
    content: "【广州市】快件已从广州转运中心发出",
    time: "2024-03-16 02:15:00",
  },
  {
    content: "商家已发货",
    time: "2024-03-15 14:20:30",
  },
]);

// 操作日志列
const logColumns = [
  {
    title: "操作时间",
    dataIndex: "time",
    width: 180,
  },
  {
    title: "操作人",
    slotName: "operator",
    width: 180,
  },
  {
    title: "操作内容",
    dataIndex: "content",
  },
];

// 操作日志数据
const operationLogs = ref([
  {
    time: "2024-03-18 15:30:00",
    operator: "系统",
    role: "系统",
    content: "订单已完成",
  },
  {
    time: "2024-03-15 14:20:30",
    operator: "商家",
    role: "商家",
    content: "订单已发货，物流单号：SF1234567890123",
  },
  {
    time: "2024-03-15 12:35:00",
    operator: "张三",
    role: "买家",
    content: "订单支付成功",
  },
  {
    time: "2024-03-15 12:34:56",
    operator: "张三",
    role: "买家",
    content: "订单创建成功",
  },
]);

// 快递公司选项
const expressOptions = [
  { label: "顺丰速运", value: "SF" },
  { label: "圆通速递", value: "YTO" },
  { label: "中通快递", value: "ZTO" },
  { label: "韵达快递", value: "YD" },
  { label: "EMS", value: "EMS" },
];

// 发货弹窗
const deliverVisible = ref(false);
const deliverForm = ref({
  company: "",
  number: "",
  remark: "",
});

// 备注弹窗
const remarkVisible = ref(false);
const remarkForm = ref({
  content: "",
});

// 获取状态步骤
const getStatusStep = (status) => {
  const stepMap = {
    pending_payment: 0,
    pending_delivery: 1,
    delivered: 2,
    completed: 3,
    cancelled: -1,
  };
  return stepMap[status] || 0;
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending_payment: "待付款",
    pending_delivery: "待发货",
    delivered: "已发货",
    completed: "已完成",
    cancelled: "已取消",
  };
  return textMap[status] || "未知状态";
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    pending_payment: "orange",
    pending_delivery: "blue",
    delivered: "green",
    completed: "cyan",
    cancelled: "red",
  };
  return colorMap[status] || "default";
};

// 获取来源文本
const getSourceText = (source) => {
  const sourceMap = {
    pc: "电脑端",
    mobile: "手机端",
    app: "APP",
    miniprogram: "小程序",
  };
  return sourceMap[source] || "未知来源";
};

// 处理发货
const handleDeliver = () => {
  deliverVisible.value = true;
};

// 提交发货
const handleDeliverSubmit = async () => {
  try {
    // TODO: 调用发货API
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("发货成功");
    deliverVisible.value = false;
  } catch (error) {
    Message.error("发货失败");
  }
};

// 取消发货
const handleDeliverCancel = () => {
  deliverForm.value = {
    company: "",
    number: "",
    remark: "",
  };
  deliverVisible.value = false;
};

// 处理备注
const handleRemark = () => {
  remarkForm.value.content = orderInfo.value.remark || "";
  remarkVisible.value = true;
};

// 提交备注
const handleRemarkSubmit = async () => {
  try {
    // TODO: 调用保存备注API
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("保存成功");
    remarkVisible.value = false;
  } catch (error) {
    Message.error("保存失败");
  }
};

// 取消备注
const handleRemarkCancel = () => {
  remarkForm.value.content = "";
  remarkVisible.value = false;
};

// 处理打印
const handlePrint = () => {
  Message.success("开始打印订单");
  // TODO: 实现打印逻辑
};

// 处理导出
const handleExport = () => {
  Message.success("开始导出订单");
  // TODO: 实现导出逻辑
};

// 处理取消订单
const handleCancel = async () => {
  try {
    // TODO: 调用取消订单API
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("订单已取消");
  } catch (error) {
    Message.error("取消失败");
  }
};

// 复制相关信息
const handleCopyOrderNo = () => {
  navigator.clipboard.writeText(orderInfo.value.orderNo);
  Message.success("订单号已复制");
};

const handleCopyTransactionId = () => {
  navigator.clipboard.writeText(orderInfo.value.transactionId);
  Message.success("交易单号已复制");
};

const handleCopyTrackingNo = () => {
  navigator.clipboard.writeText(orderInfo.value.expressNo);
  Message.success("运单号已复制");
};

const handleCopyBuyerInfo = () => {
  const buyerInfo = `
收货人：${orderInfo.value.buyer.name}
电话：${orderInfo.value.buyer.phone}
地址：${orderInfo.value.buyer.address}
  `.trim();
  navigator.clipboard.writeText(buyerInfo);
  Message.success("买家信息已复制");
};

// 刷新物流
const handleRefreshLogistics = () => {
  Message.success("物流信息已更新");
  // TODO: 实现刷新物流逻辑
};
</script>

<style lang="less" scoped>
.order-detail {
  padding: 16px;
  background-color: var(--color-bg-1);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px 20px;
    background-color: var(--color-bg-2);
    border-radius: 4px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

      .page-title {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
      }
    }
  }

  .detail-content {
    .status-card {
      margin-bottom: 16px;

      .status-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;

        .status-info {
          display: flex;
          align-items: center;
          gap: 12px;

          .status-icon {
            font-size: 32px;
            color: rgb(var(--success-6));
          }

          .status-text {
            .status-title {
              font-size: 16px;
              font-weight: 500;
              color: var(--color-text-1);
            }

            .status-desc {
              font-size: 13px;
              color: var(--color-text-3);
              margin-top: 4px;
            }
          }
        }

        .status-actions {
          display: flex;
          gap: 8px;
        }
      }

      .status-steps {
        margin-top: 32px;
      }
    }

    .detail-row {
      .detail-card {
        margin-bottom: 16px;

        .products-list {
          .product-item {
            display: flex;
            gap: 16px;
            padding: 16px 0;

            &:not(:last-child) {
              border-bottom: 1px solid var(--color-border);
            }

            .product-info {
              flex: 1;

              .product-name {
                font-size: 14px;
                font-weight: 500;
                margin-bottom: 8px;
              }

              .product-specs {
                font-size: 13px;
                color: var(--color-text-3);
                margin-bottom: 8px;
              }

              .product-price {
                .price {
                  font-size: 14px;
                  color: rgb(var(--danger-6));
                  margin-right: 8px;
                }

                .quantity {
                  font-size: 13px;
                  color: var(--color-text-3);
                }
              }
            }
          }
        }

        .order-amount {
          padding: 16px 0;

          .amount-item {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 8px;
            font-size: 13px;
            color: var(--color-text-2);

            &.total {
              margin-top: 16px;
              padding-top: 16px;
              border-top: 1px dashed var(--color-border);
              font-size: 14px;

              .total-price {
                font-size: 16px;
                font-weight: 500;
                color: rgb(var(--danger-6));
              }
            }

            span:first-child {
              margin-right: 16px;
            }

            .discount {
              color: rgb(var(--success-6));
            }
          }
        }

        .logistics-info {
          .express-info {
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 16px;
            background-color: var(--color-fill-2);
            border-radius: 4px;
            margin-bottom: 24px;

            .express-icon {
              font-size: 32px;
              color: rgb(var(--primary-6));
            }

            .express-detail {
              .express-company {
                font-size: 14px;
                font-weight: 500;
                margin-bottom: 4px;
              }

              .express-number {
                font-size: 13px;
                color: var(--color-text-2);
              }
            }
          }

          .logistics-timeline {
            padding: 0 16px;

            .timeline-content {
              .timeline-text {
                font-size: 13px;
                color: var(--color-text-1);
              }

              .timeline-time {
                font-size: 12px;
                color: var(--color-text-3);
                margin-top: 4px;
              }
            }
          }
        }

        .info-list {
          .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 16px;
            font-size: 13px;

            .label {
              width: 80px;
              color: var(--color-text-3);
            }

            .value {
              flex: 1;
              color: var(--color-text-1);
            }
          }
        }
      }
    }
  }
}

// 暗色主题适配
:deep([arco-theme="dark"]) {
  .order-detail {
    .page-header {
      background-color: var(--color-bg-2);
    }

    .detail-content {
      .status-card,
      .detail-card {
        background-color: var(--color-bg-2);
      }

      .logistics-info {
        .express-info {
          background-color: var(--color-fill-3);
        }
      }
    }
  }
}
</style>
